package hk.ust.cse.comp3111.studentSchedule;



import java.util.ArrayList;
import java.util.List;
import java.util.TimeZone;

import android.app.Fragment;
import android.content.ContentUris;
import android.content.ContentValues;
import android.database.Cursor;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.provider.CalendarContract;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

public class ImportByCourse_2 extends Fragment {
	
	TextView courseCodeSelected;
	TextView title;
	CourseDatabaseHandler db;
	Spinner spinner1, spinner2, spinner3;
	int structure;
	Button buton_import;
	int count;
	
	RegisteredClassDatabaseHandler db_register;
	long calendarID;
	long eventID;
	
	List<String> list1= new ArrayList<String>();
    List<String> list2= new ArrayList<String>();
    List<String> list3= new ArrayList<String>();
	
	@Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
 
        View rootView = inflater.inflate(R.layout.import_by_course_2, container, false);
         
        return rootView;
    }
	
	
	@Override
    public void onStart() {
    	super.onStart();
    	
    	Bundle args = getArguments();
    	String courseCode=args.getString("SELECTED");
    	courseCodeSelected=(TextView)this.getView().findViewById(R.id.courseCodeSelected);
    	title=(TextView)this.getView().findViewById(R.id.title);
    	courseCodeSelected.setText(courseCode.toString().toUpperCase());
    	//Toast.makeText(getActivity(),"HEHE "+word,Toast.LENGTH_SHORT).show();
    	
    	db=new CourseDatabaseHandler(this.getActivity());
    	List<Course> courseQuery = db.getCourseByCourseCode(courseCode.toString().toUpperCase());
    	title.setText(courseQuery.get(0).getCourseName());
    	//Toast.makeText(getActivity(),"HEHE "+title.get(0).getCourseName(),Toast.LENGTH_SHORT).show();
    	
    	courseCodeSelected.setTextColor(Color.parseColor("#6c00d7"));
    	title.setTextColor(Color.parseColor("#6c00d7"));
    	structure = courseQuery.get(0).getStructure();
    	
    	spinner1 =  (Spinner) this.getView().findViewById(R.id.spinner1);
    	spinner2 =  (Spinner) this.getView().findViewById(R.id.spinner2);
    	spinner3 =  (Spinner) this.getView().findViewById(R.id.spinner3);
    	spinner1.setVisibility(View.INVISIBLE);
    	spinner2.setVisibility(View.INVISIBLE);
    	spinner3.setVisibility(View.INVISIBLE);
    	
    	buton_import = (Button) this.getView().findViewById(R.id.buton_import);
    	
    	ArrayAdapter<String> adapter;
        
    	operate(structure,courseQuery);
    	
    	String[] string1=list1.toArray(new String[list1.size()]);
    	String[] string2=list2.toArray(new String[list2.size()]);
    	String[] string3=list3.toArray(new String[list3.size()]);
    	
    	if(structure==1 || structure==5 || structure==6)	{
    		adapter = new ArrayAdapter<String>(this.getActivity(),android.R.layout.simple_spinner_item,list1);
    		adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
            spinner1.setAdapter(adapter);
            spinner1.setVisibility(View.VISIBLE);
            count=1;
    	}
		else if (structure==2 || structure==4 ||structure==7)	{
			adapter = new ArrayAdapter<String>(this.getActivity(),android.R.layout.simple_spinner_item,list1);
    		adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
            spinner1.setAdapter(adapter);
            
            adapter = new ArrayAdapter<String>(this.getActivity(),android.R.layout.simple_spinner_item,list2);
    		adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
            spinner2.setAdapter(adapter);
            
            spinner1.setVisibility(View.VISIBLE);
            spinner2.setVisibility(View.VISIBLE);
            count=2;
			
		}
		else if(structure==3)	{
			adapter = new ArrayAdapter<String>(this.getActivity(),android.R.layout.simple_spinner_item,list1);
    		adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
            spinner1.setAdapter(adapter);
            
            adapter = new ArrayAdapter<String>(this.getActivity(),android.R.layout.simple_spinner_item,list2);
    		adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
            spinner2.setAdapter(adapter);
            
            adapter = new ArrayAdapter<String>(this.getActivity(),android.R.layout.simple_spinner_item,list3);
    		adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
            spinner3.setAdapter(adapter);
            
            spinner1.setVisibility(View.VISIBLE);
            spinner2.setVisibility(View.VISIBLE);
            spinner3.setVisibility(View.VISIBLE);
            count=3;
		}
    	
    	buton_import.setOnClickListener(new OnClickListener() {
        	
        	@Override
			public void onClick(View v) {
        		if(count==1){
        			addEvent(courseCodeSelected.getText().toString().toUpperCase(), spinner1.getSelectedItem().toString());
        		}
        		else if(count==2){
        			addEvent(courseCodeSelected.getText().toString().toUpperCase(), spinner1.getSelectedItem().toString());
        			addEvent(courseCodeSelected.getText().toString().toUpperCase(), spinner2.getSelectedItem().toString());
        		}
        		else if(count==3){
        			addEvent(courseCodeSelected.getText().toString().toUpperCase(), spinner1.getSelectedItem().toString());
        			addEvent(courseCodeSelected.getText().toString().toUpperCase(), spinner2.getSelectedItem().toString());
        			addEvent(courseCodeSelected.getText().toString().toUpperCase(), spinner3.getSelectedItem().toString());
        		}
        		
        		Toast.makeText(getActivity(),"Import "+courseCodeSelected.getText().toString().toUpperCase()+" successful!",Toast.LENGTH_SHORT).show();

			}
			
		});
    	
    	
	}
	
	public void operate(int structure, List<Course> courseQuery){
		
		int numberOfType=0;
		
		if(structure==1 || structure==5 || structure==6)	numberOfType=1;
		else if (structure==2 || structure==4 ||structure==7)	numberOfType=2;
		else if(structure==3)	numberOfType=3;
	
        if(structure==1 || structure==5 || structure==6){
        	for (Course c : courseQuery){
        		list1.add(c.getSection());
        	}
        }
        
        else if (structure==2){
        	for (Course c : courseQuery){
        		if(c.getType()==1) list1.add(c.getSection());
        		else list2.add(c.getSection());
        	}
        }
        
        else if (structure==4){
        	for (Course c : courseQuery){
        		if(c.getType()==1) list1.add(c.getSection());
        		else list2.add(c.getSection());
        	}
        }
        
		else if (structure==7){
			for (Course c : courseQuery){
        		if(c.getType()==1) list1.add(c.getSection());
        		else list2.add(c.getSection());
        	}
        }
        
		else if (structure==3){
			for (Course c : courseQuery){
        		if(c.getType()==1) list1.add(c.getSection());
        		else if(c.getType()==2) list2.add(c.getSection());
        		else list3.add(c.getSection());
        	}
			
		}
        
        
        

		
	}
	
	private void addEvent(String courseCode, String section) {
		
		db=new CourseDatabaseHandler(this.getActivity());
		Course course = db.getCourseByCourseCodeAndSection(courseCode, section);
		int loop=0;
		String ruleSub=new String();
		String WEEKDAY[]={"MO","TU","WE","TH","FR"};
		
		if(course.getRep3_weekDay()!=0){
			loop=3;
			//ruleSub=WEEKDAY[(int) (course.getRep1_weekDay()-1)]+","+WEEKDAY[(int) course.getRep2_weekDay()-1]+","+WEEKDAY[(int) course.getRep3_weekDay()];
		}
		else if (course.getRep2_weekDay()!=0){
			loop=2;
			//ruleSub=WEEKDAY[(int) (course.getRep1_weekDay()-1)]+","+WEEKDAY[(int) course.getRep2_weekDay()-1];
		}
		else if (course.getRep1_weekDay()!=0){
			loop=1;
			//ruleSub=WEEKDAY[(int) (course.getRep1_weekDay()-1)];
		}
		
		//long resu=course.getFromDate().getTime()+course.getRep1_fromTime()+j*604800000L;
		//Toast.makeText(getActivity(),"time check "+course.getFromDate().getTime()+course.getRep1_fromTime()+0*604800000,Toast.LENGTH_LONG).show();
		
		
		//Toast.makeText(getActivity(),"loop: "+loop,Toast.LENGTH_LONG).show();
		

		
		//String duration="P"+Long.toString((course.getRep1_toTime()-course.getRep1_fromTime())/1000)+"S";
		//Toast.makeText(getActivity(),"duration: "+duration,Toast.LENGTH_LONG).show();
		
		for(int i=1; i<=loop; i++){
			if(i==1){
						
				String duration="P"+Long.toString((course.getRep1_toTime()-course.getRep1_fromTime())/1000)+"S";
				
					put(course.getCourseCode()+" "+course.getSection() ,
						course.getFromDate().getTime()+course.getRep1_fromTime(),
						course.getVenue(),
						duration
							);
				
			}
			
			else if (i==2){
				
				String duration="P"+Long.toString((course.getRep2_toTime()-course.getRep2_fromTime())/1000)+"S";
				long difference=(course.getRep2_weekDay()-course.getRep1_weekDay())*86400000L;
				
				put(course.getCourseCode()+" "+course.getSection() ,
						course.getFromDate().getTime()+course.getRep2_fromTime()+difference,
						course.getVenue(),
						duration
							);
				
			}
			
			else if (i==3){
	
				String duration="P"+Long.toString((course.getRep3_toTime()-course.getRep3_fromTime())/1000)+"S";
				long difference=(course.getRep2_weekDay()-course.getRep1_weekDay())*86400000L;
				
				put(course.getCourseCode()+" "+course.getSection() ,
						course.getFromDate().getTime()+course.getRep3_fromTime()+difference,
						course.getVenue(),
						duration
							);
				
			}
			
			db_register=new RegisteredClassDatabaseHandler(this.getActivity());
			db_register.register(course, eventID);
			
			
		}
		
    	
    }
 // we use this method in order to get the ID of the calendar because
 // calendar ID is a required field in creating an event
    
    public long getCalendarID() {
    	Cursor cur = null;
    	try {
    	// provide CalendarContract.Calendars.CONTENT_URI to
    	// ContentResolver to query calendars
    		cur = this.getActivity().getContentResolver().query(CalendarContract.Calendars.CONTENT_URI,null,null,null, null);
    		if (cur.moveToFirst()) {
    			return cur.getLong(cur.getColumnIndex(CalendarContract.Calendars._ID));
    		}
    	} catch (Exception e) {
    		e.printStackTrace();
    		} finally {
		    	if (cur != null) {
		    	cur.close();
		    	}
    		}
    	return -1L;
    	}
	
	
	private void put(String title, long startTime, String venue,String duration){
		String rules = "FREQ=WEEKLY;COUNT=14";
		
		calendarID = getCalendarID();	
    	ContentValues eventValues = new ContentValues ();
    	eventValues.put(CalendarContract.Events.CALENDAR_ID,calendarID);
    	eventValues.put(CalendarContract.Events.TITLE,title);
    	eventValues.put(CalendarContract.Events.DESCRIPTION,"Added by Student Schedule");
    	eventValues.put(CalendarContract.Events.DTSTART,startTime);
    	eventValues.put(CalendarContract.Events.DURATION, duration);
    	eventValues.put(CalendarContract.Events.RRULE, rules);
    	eventValues.put(CalendarContract.Events.EVENT_LOCATION,venue);
    	eventValues.put(CalendarContract.Events.EVENT_TIMEZONE,TimeZone.getDefault().toString());
    	Uri eventUri = this.getActivity().getContentResolver().insert(CalendarContract.Events.CONTENT_URI, eventValues);
    	eventID = ContentUris.parseId(eventUri);
	}
	

}
